package com.finance3.springmvc.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class JDBCUtils {
	
	/**
	 * dbcp连接
	 * 2020/09/20
	 * 阴雨
	 */
	private static DataSource source;
	static {
		Properties pros = new Properties();
		try {
			//InputStream is=JDBCUtils.class.getClassLoader().getResourceAsStream("dbcp.properties");//这里不能用这个方法获取dbcp.properties文件，测试类正确但是springmvc加载的时候找不到路径，只能用下面的方法获取
			InputStream in=JDBCUtils.class.getClassLoader().getResourceAsStream("dbcp.properties");
			pros.load(in);
			source=BasicDataSourceFactory.createDataSource(pros);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection(){
		Connection conn;
		try {
			conn = source.getConnection();
			return conn;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 关闭连接
	 * conn,ps,rs
	 */
	public static void closeResource(Connection conn,Statement ps,ResultSet rs) {
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			ps.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 关闭连接
	 * conn,ps,rs
	 */
	public static void closeResource2(Connection conn) {
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void closeResource3(Connection conn, ResultSet rs) {
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
